package com.heartech.prediciton_wx.service.qrcode;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@Service
public class QrCodeImageService {
    public void getAndSaveQRCodeImage(String ticket) {
        String url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;

        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");

            int responseCode = con.getResponseCode();
            log.info("GET Image Response Code :: " + responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) {
                saveImageLocally(con.getInputStream(), "qrcode.jpg");
                log.info("QR Code image saved as qrcode.jpg");
            } else {
                log.info("GET request for QR code image not worked");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveImageLocally(InputStream inputStream, String fileName) throws IOException {
        String currentDir = System.getProperty("user.dir");
        String parentFolderPath = currentDir + File.separator + "image";
        String currentDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        String folderPath = parentFolderPath + File.separator + currentDateTime;
        File folder = new File(folderPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        try (OutputStream outputStream = new FileOutputStream(folderPath + File.separator + fileName)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
    }
}
